package com.gitee.wsl.platform

import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.pointed
import kotlinx.cinterop.toKString
import platform.posix.getenv
import platform.posix.getpwuid
import platform.posix.getuid
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.readBytes
import kotlinx.cinterop.usePinned
import platform.Foundation.NSData
import platform.Foundation.dataWithBytes

@OptIn(ExperimentalForeignApi::class)
internal actual fun home(): String {
    memScoped {
        val home = getenv("HOME")
        if (home != null) {
            return home.toKString()
        } else {
            val uid = getuid()
            return getpwuid(uid)!!.pointed.pw_dir!!.toKString()
        }
    }
}

//internal actual fun fileSeparator() : String = "/"

//internal actual fun pathSeparator() : String = ":"

@OptIn(ExperimentalUnsignedTypes::class, ExperimentalForeignApi::class)
fun NSData.toByteArray(): ByteArray? {
    if (bytes == null) {
        return null
    }
    return bytes!!.readBytes(length.toInt())
}

@OptIn(ExperimentalUnsignedTypes::class, ExperimentalForeignApi::class)
fun ByteArray.toNSData(): NSData? {
    if (isEmpty()) {
        return null
    }

    return usePinned {
        return@usePinned NSData.dataWithBytes(it.addressOf(0), it.get().size.toULong())
    }
}